package top.blueShark.template.controller;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.blueShark.template.common.Result;
import top.blueShark.template.common.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/common")
public class CommonController {
    private static final Logger logger = LoggerFactory.getLogger(CommonController.class);

    @Value("${file.upload.dir}")
    private String uploadDir;

    @Value("${file.upload.url-prefix}")
    private String fileUrlPrefix;

    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile file,@RequestParam Long uploadUserId) {
        Map<String, Object> data = new HashMap<>();
        String originalFilename = file.getOriginalFilename();
        logger.info("通用接口文件上传 [ originalFilename ] ：{}", originalFilename);
        // 保存文件到本地或服务器
        logger.info(file.getContentType());
        Integer index = null;
        String ext = null;

        if (originalFilename != null){
            index = StringUtils.getLastIndexOfChar(originalFilename, ".");
            ext = StringUtils.substringFromIndex(originalFilename,index);
        }
        long currentTime = System.currentTimeMillis();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String saveName = currentTime + '_' + uuid + '.' + ext;
        File userDir = new File(uploadDir, String.valueOf(uploadUserId));
        userDir.mkdirs();
        File newDest = new File(userDir, saveName);
        newDest.getParentFile().mkdirs();
        try {
            logger.info("目标文件路径：" + newDest.getAbsolutePath());
            file.transferTo(newDest);
        } catch (IOException e) {
            return Result.fail("文件保存失败！");
        }
        String SERVICE_UPLOAD_FILE_URL = fileUrlPrefix + uploadUserId + "/" + saveName;
        data.put("originalFilename", originalFilename);
        data.put("saveName", saveName);
        data.put("uploadUrl", SERVICE_UPLOAD_FILE_URL);
        return Result.success(data);
    }
}
